package com.hyc.cloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.hyc.cloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 这里是类说明.
 *
 * @className: PaymentServiceImpl
 * @author: hyc
 * @date: 2022-01-17 10:23
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String paymentInfo_OK(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + "paymentInfo_OK,id: " + id + "\t" + "O(∩_∩)O";
    }

    // 一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutFallback"
            // 超时时间降级
            , commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="4000")})
    @Override
    public String paymentInfo_TimeOut(Integer id) {
        // 测试运行时异常
//        int i = 10 /0;
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut,id: " + id + "\t" + "O(∩_∩)O，耗费3秒";
    }

    /**
     * paymentInfo_TimeOut的降级方法
     * @title paymentInfo_TimeOutFallback
     * @author hyc
     * @date 2022/1/17 11:33
     * @param id
     * @return java.lang.String
     */
    public String paymentInfo_TimeOutFallback(Integer id) {
        return "/(ㄒoㄒ)/调用支付接口超时或异常：\t"+ "\t当前线程池名字" + Thread.currentThread().getName();
    }

    @Override
    public String paymentCircuitBreaker(Integer id) {

        if (id < 0) {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName() + "\t" + "调用成功，流水号: " + serialNumber;
    }
}